package com.borened.common.boot.config;

import com.borened.common.boot.config.properties.IgnoreWhiteProperties;
import com.borened.common.boot.interceptor.AsyncRequestHeaderInterceptor;
import com.borened.common.boot.interceptor.JwtInterceptor;
import com.borened.common.boot.interceptor.RequestRateLimitInterceptor;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.TimeZone;

/**
 * webmvc 相关配置
 * <pre>
 * SpringMVC常用注解
 *  @RequestParam 用于接收和校验请求头的参数，value为参数名，可以设置是否必传和默认值等；不添加此注解则不会校验参数。
 *  @RequestBody 用于接收请求体中的复杂参数（如对象，List,Map等），一般内容格式为applicaiton/json，
 *                 不添加该注解默认接收 application/x-www-form-urlencoded 表单类型的数据。
 *  @RequestPart 用于接收内容格式为multipart/form-data 文件类型的请求。
 *
 * </pre>
 *
 * @author <boren1007@qq.com>
 * @since 2021/11/27 21:54
 */
@Slf4j
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {


    /**
     * 默认日期时间格式
     */
    public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
    /**
     * 默认日期格式
     */
    public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
    /**
     * 默认时间格式
     */
    public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";

    /**
     * 需要跳过认证的url,可以配置在security.ignore.whites属性中。静态资源等。
     */
    @Autowired
    private IgnoreWhiteProperties ignoreWhiteProperties;
    //默认日志格式
    @Value("${spring.jackson.date-format:yyyy-MM-dd HH:mm:ss}")
    private String pattern;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        //请求限流拦截器
        registry.addInterceptor(requestRateLimitInterceptor());
        //登录认证拦截器
        registry.addInterceptor(jwtInterceptor()).excludePathPatterns(ignoreWhiteProperties.getWhites());
        //异步请求参数拦截器（依赖jwtInterceptor）
        registry.addInterceptor(requestHeaderInterceptor()).excludePathPatterns(ignoreWhiteProperties.getWhites());
    }

    //全局日志格式化格式定义
    @Bean
    public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
        return builder -> builder.serializerByType(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(pattern)));
    }


    /**
     * LocalDate转换器，用于转换RequestParam和PathVariable参数
     *
     * @return
     */
    @Bean
    public Converter<String, LocalDate> localDateConverter() {
        return new Converter<String, LocalDate>() {
            @Override
            public LocalDate convert(String source) {
                return LocalDate.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT));
            }
        };
    }

    /**
     * LocalDateTime转换器，用于转换RequestParam和PathVariable参数
     *
     * @return
     */
    @Bean
    public Converter<String, LocalDateTime> localDateTimeConverter() {
        return new Converter<String, LocalDateTime>() {
            @Override
            public LocalDateTime convert(String source) {
                return LocalDateTime.parse(source, DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT));
            }
        };
    }


    /**
     * JSON序列化和反序列化消息转换器。默认使用jackson.如果使用fastjson则此配置无效。
     */
    @Bean
    public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        //jackson序列化配置
        ObjectMapper objectMapper = jackson2HttpMessageConverter.getObjectMapper();
        objectMapper.setDateFormat(new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT));
        objectMapper.setTimeZone(TimeZone.getTimeZone("GMT+8"));
        objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
        objectMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);

        // 后台Long值传递给前端精度丢失问题（JS最大精度整数是Math.pow(2,53)）
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        // simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        // simpleModule.addSerializer(BigInteger.class, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);

        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        return jackson2HttpMessageConverter;
    }

    @Bean
    public JwtInterceptor jwtInterceptor() {
        JwtInterceptor jwtInterceptor = new JwtInterceptor();
        return jwtInterceptor;
    }

    @Bean
    public AsyncRequestHeaderInterceptor requestHeaderInterceptor() {
        AsyncRequestHeaderInterceptor requestHeaderInterceptor = new AsyncRequestHeaderInterceptor();
        return requestHeaderInterceptor;
    }

    @Bean
    public RequestRateLimitInterceptor requestRateLimitInterceptor() {
        RequestRateLimitInterceptor rateLimitInterceptor = new RequestRateLimitInterceptor();
        return rateLimitInterceptor;
    }
}
